package photostock.control.servlet;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import photostock.model.Album;
import photostock.model.User;
import photostock.model.UserItem;
import photostock.view.WebPage;
import photostock.view.WidgetFactory;

/**
 * Servlet implementation class Welcome
 */
public class Welcome extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
 	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

			HttpSession session = request.getSession();
			User u = (null == session.getAttribute("user")) ? new User("shared") : (User)session.getAttribute("user");
			WebPage page = WidgetFactory.getDefaultPage();
			//WidgetFactory.setStyle(page, "default");
			u.initChildrenItems();
			if (!u.isLogged()) {
				Album al = new Album();
				session.setAttribute("album", al);	
				WidgetFactory.initAlbum(page, u, al);
				page.getBody().setAttribute("onload", "setDocStyle('default')");
			} else {
				if (((Album)session.getAttribute("album")).getName().equals("shared")) {
					page.getElement("contentMain").setContent(WidgetFactory.getAlbumSet(u.getChildrenItems()));
					page.getBody().setAttribute("onload", "setDocStyle('default')");
				} else {
					WidgetFactory.initAlbum(page, u, (Album)session.getAttribute("album"));
					page.getBody().setAttribute("onload", "setDocStyle('" + ((Album)session.getAttribute("album")).getSkin() + "');");
				}
			}
			WidgetFactory.initUser(page, u);
			WidgetFactory.initMenu(page, u.getType());
			response.setContentType("text/html");
			response.getWriter().write(page.toString());			
			return;
	}
	
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		UserItem.setOriPath(getServletContext().getRealPath("/images/albums"));
	}
}
